package com.jwmp.youkeju.web.servlet;

import com.jwmp.rbac.domain.Employee;
import com.jwmp.rbac.service.IEmployeeService;
import com.jwmp.rbac.service.impl.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private IEmployeeService service = new EmployeeServiceImpl();

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 验证码处理
        String reqRandomCode = req.getParameter("randomCode");
        HttpSession session = req.getSession();
        Object sessionRomdomCode = session.getAttribute("RANDOMCODE_IN_SESSION");
        if(sessionRomdomCode == null || !sessionRomdomCode.equals(reqRandomCode)){
            req.setAttribute("errorMsg","亲，验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }
        session.removeAttribute("RANDOMCODE_IN_SESSION");

        // 账号简单验证
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Employee emp = service.login(username, password);
        if (emp == null) {
            req.setAttribute("errorMsg","亲，账号或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }


        // 登录成功,记住账号3个月
        session.setAttribute("EMPLOYEE_IN_SESSION",emp);
        Cookie cookie = new Cookie("username", username);
        Boolean remeberMe = Boolean.valueOf(req.getParameter("remeberMe"));
        if (remeberMe) {
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30 * 3);
        }else{
            cookie.setMaxAge(0);
        }
        resp.addCookie(cookie);


        resp.sendRedirect("/admin");
    }
}
